import React, { useEffect, useRef, useMemo } from 'react';
import { Navigate, useLocation, useNavigate } from 'react-router-dom';
import { useAuth } from '../contexts/AuthContext';
import { useMessage } from '../contexts/MessageContext';
import { routeConfig } from '../config/routes';

const RoutePermissionGuard = ({ children }) => {
    const { isAuthenticated, isLoading, user } = useAuth();
    const location = useLocation();
    const navigate = useNavigate();
    const hasShownMessageRef = useRef(false);
    const { showMessage } = useMessage(); // 使用 MessageContext

    // 获取当前路由配置
    const getCurrentRoute = (pathname) => {
        // 标准化路径 - 移除尾随斜杠
        const normalizedPath = pathname.replace(/\/$/, '') || '/';
        return routeConfig.find(route => route.path === normalizedPath);
    };

    // 检查路由权限
    const checkRoutePermission = (route, user) => {
        // 标准化路径 - 移除尾随斜杠
        const normalizedPath = location.pathname.replace(/\/$/, '') || '/';

        // 优先检查：已登录用户访问登录页，直接重定向到仪表盘
        if (isAuthenticated && normalizedPath === '/login') {
            return {
                allowed: false,
                redirectTo: '/dashboard',
                reason: 'ALREADY_LOGGED_IN'
            };
        }

        if (!route) return { allowed: true }; // 路由不存在时允许通过，由404处理

        const { meta } = route;
        if (!meta) return { allowed: true }; // 没有权限配置时允许通过

        // 检查是否需要登录
        if (meta.requireAuth !== false && !isAuthenticated) {
            return {
                allowed: false,
                redirectTo: '/login',
                reason: 'REQUIRE_LOGIN'
            };
        }

        // 检查角色权限
        if (meta.roles && meta.roles.length > 0) {
            const userRoles = user?.roles || [];
            const hasPermission = meta.roles.some(role => userRoles.includes(role));
            if (!hasPermission) {
                return {
                    allowed: false,
                    redirectTo: '/403', // 权限不足页面
                    reason: 'INSUFFICIENT_PERMISSION'
                };
            }
        }

        // 检查自定义权限
        if (meta.permissions && meta.permissions.length > 0) {
            const userPermissions = user?.permissions || [];
            const hasPermission = meta.permissions.some(permission =>
                userPermissions.includes(permission)
            );
            if (!hasPermission) {
                return {
                    allowed: false,
                    redirectTo: '/403',
                    reason: 'INSUFFICIENT_PERMISSION'
                };
            }
        }

        // 检查是否为管理员专用页面
        if (meta.adminOnly && !user?.isAdmin) {
            return {
                allowed: false,
                redirectTo: '/403',
                reason: 'ADMIN_ONLY'
            };
        }

        return { allowed: true };
    };

    // 使用 useMemo 来稳定权限检查结果
    const permissionResult = useMemo(() => {
        // 如果正在加载，返回允许状态，让其他组件处理加载
        if (isLoading) {
            return { allowed: true };
        }

        const currentRoute = getCurrentRoute(location.pathname);
        return checkRoutePermission(currentRoute, user);
    }, [location.pathname, user, isAuthenticated, isLoading]);

    // 使用 useEffect 来处理重定向和消息显示
    useEffect(() => {
        if (!isLoading && !permissionResult.allowed && !hasShownMessageRef.current) {
            const messages = {
                'REQUIRE_LOGIN': '请先登录再访问该页面',
                'INSUFFICIENT_PERMISSION': '权限不足，无法访问该页面',
                'ADMIN_ONLY': '该页面仅限管理员访问',
                'ALREADY_LOGGED_IN': '您已登录，正在跳转到仪表盘'
            };

            const messageText = messages[permissionResult.reason];
            if (messageText) {
                // 对于已登录用户访问登录页，显示信息提示而非警告
                const messageType = permissionResult.reason === 'ALREADY_LOGGED_IN' ? 'info' : 'warning';
                showMessage(messageType, messageText);
                hasShownMessageRef.current = true;

                // 保存当前尝试访问的页面，登录后可以重定向回来
                const state = permissionResult.reason === 'REQUIRE_LOGIN'
                    ? { from: location }
                    : undefined;

                // 使用 navigate 进行重定向（先判断再跳转）
                setTimeout(() => {
                    navigate(permissionResult.redirectTo, { replace: true, state });
                }, 300);
            }
        }
    }, [permissionResult.allowed, permissionResult.reason, location.pathname, isLoading, navigate, showMessage, location]);

    // 重置消息显示标记当路径改变时
    useEffect(() => {
        hasShownMessageRef.current = false;
    }, [location.pathname]);

    // 如果正在加载，让AuthGuard处理加载状态
    if (isLoading) {
        return children;
    }

    // 如果权限检查不通过，显示加载状态（等待重定向）
    if (!permissionResult.allowed) {
        return (
            <div style={{
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center',
                height: '100vh',
                background: 'linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%)',
            }}>
                <div style={{
                    background: 'rgba(255, 255, 255, 0.95)',
                    borderRadius: 20,
                    padding: '32px 48px',
                    textAlign: 'center',
                    boxShadow: '0 20px 40px rgba(0, 0, 0, 0.08)',
                    color: '#475569',
                    fontSize: '16px',
                    fontWeight: 500
                }}>
                    正在跳转...
                </div>
            </div>
        );
    }

    // 权限检查通过，渲染子组件
    return children;
};

export default RoutePermissionGuard;
